import scrapy
import json
from scrapys.wudiSpyder.wudiSpyder.items import OddsSportteryMatchItem, \
    HistoryOddsSportteryMatchItem, HistoryScoreSportteryMatchItem, ResultSportteryMatchItem
from scrapys.wudiSpyder.wudiSpyder.db_utils import DBUtils
from urllib.parse import urlencode
'''
负责更新竞猜网的奖金及比赛结果
'''
class SportteryFootballBonusSpider(scrapy.Spider):
    name = "SportteryFootballBonusSpider"
    allowed_domains = ["webapi.sporttery.cn"]

    def __init__(self, *args, **kwargs):
        super(SportteryFootballBonusSpider, self).__init__(*args, **kwargs)
        self.db = DBUtils()

    def start_requests(self):
        result_matches = self.db.get_un_match_result_list_matches()
        for ss_match in result_matches:
            reapi_params = {
                'matchId': ss_match['match_id']
            }
            # 找到比分
            yield scrapy.Request(
                url=f"https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry?clientCode=3001&{urlencode(reapi_params)}",
                callback=self.parse_update_result_match,
                meta={'match_info': ss_match}
            )
        # 从数据库获取需要更新奖金的的比赛，为停售的比赛
        matches = self.db.get_unscraped_matches()
        for match in matches:
            # 中国竞彩网的API请求参数
            api_params = {
                'matchId': match['match_id']
            }
            # 找奖金
            yield scrapy.Request(
                url = f"https://webapi.sporttery.cn/gateway/jc/football/getFixedBonusV1.qry?clientCode=3001&{urlencode(api_params)}",
                callback = self.parse_match,
                meta={'match_info': match}
            )
        score_matches = self.db.get_unscore_matches()
        for s_match in score_matches:
            sapi_params = {
                'matchId': s_match['match_id']
            }
            # 找到比分
            yield scrapy.Request(
                url = f"https://webapi.sporttery.cn/gateway/uniform/fb/getMatchScoreV1.qry?{urlencode(sapi_params)}",
                callback = self.parse_match_score,
                meta={'match_info': s_match}
            )
        # 关闭数据库连接
        self.db.close()


    # 处理 胜负彩 停售时间及其他信息
    def parse_match_score(self, response):
        res = json.loads(response.text)
        v = res.get("value")
        matchStatus = v.get("matchStatus")
        if matchStatus =="6":# 6 比赛结束。4，比赛未开始，5比赛中
            # 保存比赛结果
            score_item = HistoryScoreSportteryMatchItem()
            sectionsNos = v.get("sectionsNos")
            '''
             "sectionsNos": [
            {
                "score": "1:0",
                "sectionNo": 1
            },
            {
                "score": "4:1",
                "sectionNo": 2
            }
        ]
            '''
            if sectionsNos:
                score_item["matchId"] = v.get("matchId")
                score_item["sectionsNo1"] = sectionsNos[0].get("score")
                score_item["sectionsNo999"] = sectionsNos[1].get("score")
            yield score_item

    # 处理 胜负彩 停售时间及其他信息
    def parse_match(self, response):
        res = json.loads(response.text)
        v = res.get("value")
        oddsHistory = v.get("oddsHistory")
        if oddsHistory:
            matchId = oddsHistory.get("matchId")
            hadList = oddsHistory.get("hadList")
            hhadList = oddsHistory.get("hhadList")
            ttgList = oddsHistory.get("ttgList")
            hafuList = oddsHistory.get("hafuList")
            crsList = oddsHistory.get("crsList")

            singleList = oddsHistory.get("singleList")
            print("获取奖金。。。",matchId)
            spf_s,spf_p,spf_f = 0,0,0
            if hadList:
                had = hadList[-1]
                spf_s = float(had.get("h"))
                spf_p = float(had.get("d"))
                spf_f = float(had.get("a"))
            spf_bonus = "{},{},{}".format(spf_s, spf_p, spf_f)

            rspf_s,rspf_p,rspf_f = 0,0,0
            goalLine = "0"
            if hhadList:
                hhad = hhadList[-1]
                rspf_s = float(hhad.get("h"))
                rspf_p = float(hhad.get("d"))
                rspf_f = float(hhad.get("a"))
                goalLine = hhad.get("goalLine")
            rspf_bonus = "{},{},{}".format(rspf_s, rspf_p, rspf_f)

            ss, sp, sf,ps, pp, pf,fs, fp, ff = 0,0,0,0,0,0,0,0,0
            if hafuList:
                org = hafuList[-1]
                ss = float(org.get("hh"))
                sp = float(org.get("hd"))
                sf = float(org.get("ha"))
                ps = float(org.get("dh"))
                pp = float(org.get("dd"))
                pf = float(org.get("da"))
                fs = float(org.get("ah"))
                fp = float(org.get("ad"))
                ff = float(org.get("aa"))

            bqc_bonus = "{},{},{},{},{},{},{},{},{}".format(ss, sp, sf, ps, pp, pf, fs, fp, ff)

            g0, g1, g2, g3, g4, g5, g6, g7 = 0,0,0,0,0,0,0,0
            if ttgList:
                org = ttgList[-1]
                g0 = float(org.get("s0"))
                g1 = float(org.get("s1"))
                g2 = float(org.get("s2"))
                g3 = float(org.get("s3"))
                g4 = float(org.get("s4"))
                g5 = float(org.get("s5"))
                g6 = float(org.get("s6"))
                g7 = float(org.get("s7"))

            ttg_bonus = "{},{},{},{},{},{},{},{}".format(g0, g1, g2, g3, g4, g5, g6, g7)

            s10, s20, s21, s30, s31, s32, s40, s41, s42, s50, s51, s52, ss = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            s00,s11, s22, s33, sp = 0,0, 0, 0, 0
            s01, s02, s12, s03, s13, s23, s04, s14, s24, s05, s15, s25, sf = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            if crsList:
                crs = crsList[-1]
                s10, s20, s21 = crs.get("s01s00"), crs.get("s02s00"), crs.get("s02s01")
                s30, s31, s32 = crs.get("s03s00"), crs.get("s03s01"), crs.get("s03s02"),
                s40, s41, s42 = crs.get("s04s00"), crs.get("s04s01"), crs.get("s04s02")
                s50, s51, s52, ss = crs.get("s05s00"), crs.get("s05s01"), crs.get("s05s00"), crs.get("s-1sh")

                s00,s11, s22, s33, sp = crs.get("s00s00"),crs.get("s01s01"), crs.get("s02s02"), crs.get("s03s03"), crs.get("s-1sd")

                s01, s02, s12 = crs.get("s00s01"), crs.get("s00s02"), crs.get("s01s02")
                s03, s13, s23= crs.get("s00s03"), crs.get("s01s03"), crs.get("s02s03"),
                s04, s14, s24 = crs.get("s00s04"), crs.get("s01s04"), crs.get("s02s04")
                s05, s15, s25, sf = crs.get("s00s05"), crs.get("s01s05"), crs.get("s02s05"), crs.get("s-1sa")

            s_b = f"{s10}, {s20}, {s21}, {s30}, {s31}, {s32}, {s40}, {s41}, {s42}, {s50}, {s51}, {s52}, {ss}"
            s_p = f"{s00},{s11}, {s22}, {s33}, {sp}"
            s_f = f"{s01}, {s02}, {s12}, {s03}, {s13}, {s23}, {s04}, {s14}, {s24}, {s05}, {s15}, {s25}, {sf}"

            crs_bonus = f"{s_b},{s_p},{s_f}"

            # 是否单关解析
            spf_single = 0
            rspf_single = 0
            spf_single_list = list(filter(lambda x: x["poolCode"] == 'HAD', singleList))
            if spf_single_list:
                spf_single = spf_single_list[0]["single"]

            rspf_single_list = list(filter(lambda x: x["poolCode"] == 'HHAD', singleList))
            if rspf_single_list:
                rspf_single = rspf_single_list[0]["single"]

            # 再把原始的奖金数据及开奖数据保存到数据库里面
            sectionsNo999 = v.get("sectionsNo999")
            singleList = oddsHistory.get("singleList")
            crsList = oddsHistory.get("crsList")
            hadList = oddsHistory.get("hadList")
            hafuList = oddsHistory.get("hafuList")
            hhadList = oddsHistory.get("hhadList")
            ttgList = oddsHistory.get("ttgList")


            # 保存奖金指数
            odd_item = HistoryOddsSportteryMatchItem()
            # 判断是否已经结束，如果结束，就标记一下销售字段
            if sectionsNo999:
                odd_item['matchStatus'] = "finish"
                odd_item['sellStatus'] = "4"    # 4表示已经停止销售
            else:
                odd_item = OddsSportteryMatchItem()
            # 保存奖金指数

            odd_item["matchId"] = matchId
            odd_item["spf_bonus"] = spf_bonus
            odd_item["rspf_bonus"] = rspf_bonus
            odd_item["ttg_bonus"] = ttg_bonus
            odd_item["bqc_bonus"] = bqc_bonus
            odd_item["crs_bonus"] = crs_bonus
            odd_item["spf_single"] = spf_single
            odd_item["rspf_single"] = rspf_single
            odd_item["goalLine"] = goalLine
            odd_item["singleList"] = json.dumps(singleList)
            odd_item["crsList"] = json.dumps(crsList)
            odd_item["hadList"] = json.dumps(hadList)
            odd_item["hafuList"] = json.dumps(hafuList)
            odd_item["hhadList"] = json.dumps(hhadList)
            odd_item["ttgList"] = json.dumps(ttgList)

            yield odd_item

        # 获取开奖信息
    def parse_update_result_match(self, response):
        res = json.loads(response.text)
        v = res.get("value")
        oddsHistory = v.get("oddsHistory")
        if oddsHistory:
            matchId = oddsHistory.get("matchId")
            matchResultList = v.get("matchResultList")
            if matchResultList:
                # 保存奖金指数
                odd_item = ResultSportteryMatchItem()

                odd_item["matchId"] = matchId
                odd_item["matchResultList"] = json.dumps(matchResultList)

                yield odd_item
